//
//  HttpRequest.m
//  youyue
//
//  Created by oceans on 2018/8/15.
//

#import "HttpRequest.h"
#import <AFNetworking/AFNetworking.h>
#import "OAuthAPI.h"
#import <CoreTelephony/CTCellularData.h>
#import "Utility.h"
#import "TipManager.h"

@implementation MetaModel

- (instancetype)initWithDic:(NSDictionary *)dic {
    self = [super init];
    if (self) {
        
        _totalCount = [[dic objectForKey:@"totalCount"] intValue];
        _pageCount = [[dic objectForKey:@"pageCount"] intValue];
        _currentPage = [[dic objectForKey:@"currentPage"] intValue];
        _perPage = [[dic objectForKey:@"perPage"] intValue];
    }
    return self;
}
@end

@implementation HttpRequest

+ (int)checkNetWorkPermission
{
    CTCellularData *cellularData = [[CTCellularData alloc]init];
    CTCellularDataRestrictedState state = cellularData.restrictedState;
    return state;
}

+ (void)addRequestHeadersSessionManager:(AFHTTPSessionManager *)manager url:(NSString*)url {
    
    // 接口验证规则
    if ([url hasPrefix:kget_access_token]) {
        return;
    }
    
    [manager.requestSerializer setValue:[NSString stringWithFormat:@"Bearer %@", [OAuthAPI getAccessToken]] forHTTPHeaderField:@"Authorization"];
}

+ (void)getURL:(NSString *)url paras:(NSDictionary *)paras showProgress:(BOOL)showProgress successful:(HttpRequestSuccessfulBlock)successful failed:(HttpRequestFailedBlock)failed {
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [self addRequestHeadersSessionManager:manager url:url];
    __block UIView * progressView = nil;
    if (showProgress) {
        progressView = [self currentView];
        [MBProgressHUD showHUDAddedTo:progressView animated:NO];
    }
    [manager GET:url parameters:paras progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (progressView) {
            [MBProgressHUD hideHUDForView:progressView animated:NO];
        }
        NSLog(@"%@", responseObject);
        [self handelResult:task respose:responseObject error:nil success:YES successBlock:successful failedBlock:failed];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (progressView) {
            [MBProgressHUD hideHUDForView:progressView animated:NO];
        }
        NSLog(@"%@", error.description);
        [self handelResult:task respose:nil error:error success:NO successBlock:successful failedBlock:failed];
    }];
}

+ (void)postURL:(NSString *)url paras:(NSDictionary *)paras showProgress:(BOOL)showProgress successful:(HttpRequestSuccessfulBlock)successful failed:(HttpRequestFailedBlock)failed {
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [self addRequestHeadersSessionManager:manager url:url];
    __block UIView * progressView = nil;
    if (showProgress) {
        progressView = [self currentView];
        [MBProgressHUD showHUDAddedTo:progressView animated:NO];
    }
    [manager POST:url parameters:paras progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (progressView) {
            [MBProgressHUD hideHUDForView:progressView animated:NO];
        }
        NSLog(@"%@", responseObject);
        [self handelResult:task respose:responseObject error:nil success:YES successBlock:successful failedBlock:failed];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@", error.description);
        if (progressView) {
            [MBProgressHUD hideHUDForView:progressView animated:NO];
        }
        [self handelResult:task respose:nil error:error success:NO successBlock:successful failedBlock:failed];
    }];
}

+ (void)handelResult:(NSURLSessionDataTask*)task respose:(id)responseObject error:(NSError*)error success:(BOOL)success successBlock:(HttpRequestSuccessfulBlock)successB failedBlock:(HttpRequestFailedBlock)failedB {
    
    if (success) {
        if ([[responseObject objectForKey:@"code"] intValue] == 200) {
            if (successB) {
                successB(responseObject);
            }
        }else {
            if ([[responseObject objectForKey:@"code"] intValue] == 403) {
                [[UserModel shared] logoutWith401];
            }
            [TipManager showTip:[responseObject objectForKey:@"msg"]];
            if (failedB) {
                failedB([[responseObject objectForKey:@"code"] intValue], [responseObject objectForKey:@"msg"]);
            }
        }
    }else {
        [TipManager showTip:@"网络连接失败"];
    }
}

+ (void)uploadImage:(NSString *)url paras:(NSDictionary *)paras image:(NSData *)image showProgress:(BOOL)showProgress successful:(HttpRequestSuccessfulBlock)successful failed:(HttpRequestFailedBlock)failed {
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain", @"multipart/form-data", @"application/json", @"text/html", @"image/jpeg", @"image/png", @"application/octet-stream", @"text/json", nil];
    [self addRequestHeadersSessionManager:manager url:url];
    [manager POST:url parameters:paras constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        [formData appendPartWithFileData:image name:@"imageFile" fileName:@"imageFile" mimeType:@"image/jpeg"];
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"%@", responseObject);
        [self handelResult:task respose:responseObject error:nil success:YES successBlock:successful failedBlock:failed];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@", error.description);
        [self handelResult:task respose:nil error:error success:NO successBlock:successful failedBlock:failed];
    }];
}

+ (UIView*)currentView {
    
    UIWindow * window = [[UIApplication sharedApplication] keyWindow];
    if (window.windowLevel != UIWindowLevelNormal)
    {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for(UIWindow * tmpWin in windows)
        {
            if (tmpWin.windowLevel == UIWindowLevelNormal)
            {
                window = tmpWin;
                break;
            }
        }
    }
    
    UIView *frontView = [[window subviews] objectAtIndex:0];
    id nextResponder = [frontView nextResponder];
    
    if ([nextResponder isKindOfClass:[UIViewController class]]) {
        return frontView;
    }else {
        if (window.rootViewController.presentedViewController == nil) {
            return window.rootViewController.view;
        }else {
            return window.rootViewController.presentedViewController.view;
        }
    }
}

@end
